#include "projectHeader.h"

void processDelete()
{
				
				pthread_mutex_lock(&indexMutex);
				list<indexFileMetaInfo>::iterator it;
							bool permFileAlreadyExist=false;
							bool passexist=false;
							bool activateFlooding=false;
							char passwordForDelete[21];
							memset(&passwordForDelete[0],'\0',21);
							multimap<string,int>:: iterator it1;
							for(it=indexFileMetaInfoList.begin();it!=indexFileMetaInfoList.end();it++)
							{
								if (!strcmp(delFileName,(*it).originalFileName) && (!strcmp((char*)(*it).fileNonceValue,delNonce)))
								{
												
												//string str1 ((const char*)delSHA1,40);
												
												for(it1=indexSHA1Map.begin();it1!=indexSHA1Map.end();it1++)
												{		
													//it2 = indexSHA1Map.find(sha1);
													if(strcmp((const char*)(*it1).first.c_str(),delSHA1)==0 && ((*it1).second==(*it).numFileName) )
													{
														//	it1=indexSHA1Map.find(str1);
														permFileAlreadyExist=true;
														if((*it).filePassword[0] != '\0')
														{
															passexist=true;
															memcpy(&passwordForDelete[0],&((*it).filePassword[0]),20);
														}
														//printf("\nPAssword is:%s\n",(*it).filePassword);
													

													break;
													}
												}
												if(permFileAlreadyExist)
												{

													break;
												}
						
								}
							}
				pthread_mutex_unlock(&indexMutex);
			bool deleteOnCurrentNode =false;
			bool wasRandGen=false;
				if(!passexist)
				{
					char deleteConform[5];
					//printf("We will not be flooding\n");
					printf("Do you want to generate a random password?\n");
					scanf("%s",deleteConform);
					if(deleteConform[0] == 'y' || deleteConform[0] == 'Y')
					{
						
						memset(passwordForDelete, '\0', 20);
						for(int k=0;k<20;k++)
						{
							generateRandChar(&passwordForDelete[k]);
						
						}
						passwordForDelete[0]='g';
						wasRandGen=true;
						deleteOnCurrentNode =false;
						activateFlooding = true;
					}
				}
				else
				{
						activateFlooding = true;
				}
			
			
			if(!activateFlooding)
			{
				//printf("No Delete action will be taken.\n");
			}
			else
			{
				//generate new nonce and check if it is same as the given nonce. If yes delete the file on current node. Else only flood the delete request.

				unsigned char deleteNonce[20];
				memset(&deleteNonce[0],'\0',20);
				
				
				SHA1((unsigned char*)passwordForDelete, 20, deleteNonce);
				char formattedNonce[41];
				memset(&formattedNonce[0],'\0',41);
				for (int i =0 ;i< 20 ;i++)
				{
					unsigned char change[3] = {0};
					sprintf((char*)change, "%2.2x", deleteNonce[i]);
					sprintf((char*)formattedNonce+2*i,"%s",change);
				}
				if(wasRandGen == false)
				{
				if(strncmp(formattedNonce,delNonce,40)==0)
				{
					deleteOnCurrentNode=true;
				}
				if(deleteOnCurrentNode)
				{
					// Will delete the file and indexing data from the current node.
					pthread_mutex_lock(&indexMutex);
									char appendDFileName[256];
									char appendMFileName[256];
									memset(&appendMFileName[0],'\0',256);
									memset(&appendDFileName[0],'\0',256);

									//numfileId=numFileNameCounter++;

									sprintf(appendDFileName, "/%d.data", (*it).numFileName);
									sprintf(appendMFileName, "/%d.meta", (*it).numFileName);
									
									char newNumDataFile[256];
									char newNumMetaFile[256];
									memset(newNumDataFile, '\0', 256);
									memset(newNumMetaFile, '\0', 256);
									
									memcpy(newNumDataFile,homeDir,strlen(homeDir));
									strcat(newNumDataFile,"/files");
									
									//http://www.linuxquestions.org/questions/programming-9/mkdir-in-c-setting-wrong-permissions-613250/
									//mkdir(newNumDataFile,S_IRWXU | S_IRWXG | S_IRWXO);
									strcat(newNumDataFile,appendDFileName); //Change it to variable numebr file generated in indexing above
									

									memcpy(newNumMetaFile,homeDir,strlen(homeDir));
									strcat(newNumMetaFile,"/files");
									//mkdir(newNumMetaFile,S_IRWXU | S_IRWXG | S_IRWXO);
									//http://www.linuxquestions.org/questions/programming-9/mkdir-in-c-setting-wrong-permissions-613250/
									
									strcat(newNumMetaFile,appendMFileName); //Change it to variable numebr file generated in indexing above
							//		printf("DELETE: Data File Path is: %s\n",newNumDataFile);
							//		printf("DELETE: Meta File Path is: %s\n",newNumMetaFile);
										
									
									//Retain the cache size if file is part of the Cache.
									if((*it).isInCache)
									{
										remainingCacheSizeInBytes+=(*it).filesize;
									}
									//printf("-------------------11111111----------------");
									// Now delete all the index structures entries.
									
									map<int,searchResponseInfo>:: iterator searchIt;
									for(searchIt=indexSearchResponseMap.begin();searchIt != indexSearchResponseMap.end();searchIt++)
									{
										if( !strncmp((const char*)(*searchIt).second.fileID,(const char*)(*it).fileID,20))
										{
											indexSearchResponseMap.erase(searchIt);
											break;
										}
									}
									//printf("-------------------11111111----------------");
									list<bitVectorIndexItem>:: iterator bvIt;
									for(bvIt=indexBitVectoreList.begin();bvIt != indexBitVectoreList.end();bvIt++)
									{
										if((*bvIt).numFileName == (*it).numFileName)
										{
											indexBitVectoreList.erase(bvIt);
											break;
										}
									}
									//printf("-------------------11111111----------------");
									map<int,string>::iterator it3;
									
									it3=numToFileIdMap.find((*it).numFileName);
									numToFileIdMap.erase(it3);
									indexSHA1Map.erase(it1);
									indexFileMetaInfoList.erase(it);
									

	//printf("-------------------11111111----------------");
								remove(newNumDataFile);
									remove(newNumMetaFile);

								//printf("File Deleted.\n");	
								
					pthread_mutex_unlock(&indexMutex);
				
				}

				}
				// Flood the delete req to all the other nodes.
							msgHeaderClass  deleteHeader;
							unsigned char *buff1;
							char* msg = (char*)"DELT";

							//printf("NON BEACON ACCEPT : NodeID is %s\n",nodeInstanceId);
							deleteHeader.messageType=0xBC;
							buff1=GetUOID((char *)nodeInstanceId,msg,buf, sizeof(buf));
							memcpy(deleteHeader.UOID,buf,20);
							deleteHeader.ttlInHeader=ttl;
							//deleteHeader.msgDataLength=40;
							
							

							queueItem msgToBePushed;
							msgToBePushed.msgHeader.messageType=deleteHeader.messageType;
							memcpy(msgToBePushed.msgHeader.UOID,deleteHeader.UOID,20);
							msgToBePushed.msgHeader.ttlInHeader=deleteHeader.ttlInHeader;	
							

							char fileSpec[1024];
							memset(&fileSpec[0],'\0',1024);
							int len=0;
							memcpy(&fileSpec[len],"filename=",strlen("filename="));
							len+=strlen("filename=");
							memcpy(&fileSpec[len],delFileName,strlen(delFileName));
							len+=strlen(delFileName);
							memcpy(&fileSpec[len],"\n",1);
							len+=1;
							
							memcpy(&fileSpec[len],"sha1=",strlen("sha1="));
							len+=strlen("sha1=");
							memcpy(&fileSpec[len],delSHA1,40);
							len+=40;
							memcpy(&fileSpec[len],"\n",1);
							len+=1;
				
							memcpy(&fileSpec[len],"nonce=",strlen("nonce="));
							len+=strlen("nonce=");
							memcpy(&fileSpec[len],delNonce,40);
							len+=40;
							memcpy(&fileSpec[len],"\n",1);
							len+=1;

							memcpy(&fileSpec[len],"password=",strlen("password="));
							len+=strlen("password=");
							memcpy(&fileSpec[len],passwordForDelete,20);
							len+=20;
							memcpy(&fileSpec[len],"\n",1);
							len+=1;
							
							msgToBePushed.msgHeader.msgDataLength=len;
							memcpy(&msgToBePushed.dataBuf[0],&fileSpec[0],len);


							pthread_mutex_lock(&eventQueueMutex);
					
								
								eventQueue.push_back(msgToBePushed);
								//printf("Read Thread:MSG Pushed to Event Dispatcher.\n");
								pthread_cond_broadcast(&eventQueueCV);

							pthread_mutex_unlock(&eventQueueMutex);


			
			}



	return;
}


